import 'dart:convert';
import 'dart:io';

import 'package:data_table_2/data_table_2.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/views/base/MaterialAddVC.dart';
import 'package:yuellyfactory/views/base/MaterialEditParmVC.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshTree.dart';
import '../../util/AuthUtil.dart';
import '../../util/BaseRequest.dart';

import '../../util/GlobalData.dart';
import '../../util/MathUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../Controller/MaterialController.dart';
import '../dto/PriceMaterial.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';
import '../dto/PriceSerial.dart';

class MaterialVC extends StatefulWidget {
  final MaterialController partController;
  const MaterialVC({super.key, required this.partController});

  @override
  State<MaterialVC> createState() => _MaterialVCState();
}

class _MaterialVCState extends State<MaterialVC> {
  final formKey = GlobalKey<ShadFormState>();
  PricePart pricePart=PricePart();
  // Map<String,List<PricePart>> allParts={};
  final dialogKey = GlobalKey<ShadFormState>();

  Map<String,bool> showMaps={};

  List<PricePart> partDatas=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.partController.refreshPricePart=(PricePart part){
      debugPrint('刷新${part.parentId}');
      if(part.parentId !='0'){
        debugPrint('刷新${part.parentId}');
        pricePart=part;
        setState(() {
        });
        getDetail();

      }
    };
  }



  void getDetail(){

    var parm={"id":pricePart.id};
    BaseRequest.postHttp("price/partdetail",parameters:parm , canTip: false, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List<PricePart> allParts=[];
        var part=PricePart.fromJson(datas);
        allParts.add(part);
        // for(var i=0;i<datas.length;i++){
        //   var item=datas[i];
        //   var part=PricePart.fromJson(item);
        //   allParts.add(part);
        // }
        partDatas=allParts;
        setState(() {

        });
      }
    }, onError: (error){

    });
  }

  getCrumbName(PricePart partData){
    List list= ViewUtil.crumbList(partData.id,GlobalData.baseData);
    var name="";
    for(var i=0;i<list.length;i++){
      PricePart part=list[i];
      name=name+part.name;
      if(i!=list.length-1){
        name="$name > ";
      }
    }
    return name;
  }

  getCrumbView(){
    List<Widget> views=[];
    List list= ViewUtil.crumbList(pricePart.id,GlobalData.baseData);
    for(var i=0;i<list.length;i++){
      PricePart part=list[i];
      views.add(
          GestureDetector(onTap: (){
            eventBus.fire(EventRefreshTree(part.id));
          },child: Text(part.name,style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),));
      if(i!=list.length-1){
        views.add(Text(" > ",style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),));
      }

    }
    return Row(children: views);
  }


  List<Widget> materialView(){
    List<Widget> widgets=[];

    for(PricePart partData in partDatas){
      countPrice(partData);
      widgets.add(materialItemView(partData));
    }
    return widgets;
  }

  checkHasUseParm(String rule,List globalParm,Map<String,PriceParm> canShow){
    for(PriceParm parm in globalParm){
      if(rule.contains(parm.id)){
        if(!canShow.containsKey(parm.id)){
          canShow[parm.id]=parm;
        }
      }
    }
  }

  List<Widget> getGlobalPara(PricePart partData){


    Map<String,PriceParm> canShow={};

    {
      String materialRule= partData.materialRule;
      String rule=partData.rule;
      for(PriceParm parm in partData.childParmList){
        String childRule=parm.rule;
        if(childRule.isNotEmpty){
          checkHasUseParm(childRule, partData.parmList, canShow);
        }
      }
      checkHasUseParm(rule, partData.parmList, canShow);
      checkHasUseParm(materialRule, partData.parmList, canShow);
    }

    List<PriceParm> newParms=[];
    for (var value in canShow.values) {
      newParms.add(value);
    }


    List<Widget> widgets=[];
    widgets.add(SizedBox(width: ViewUtil.screenWidth(15),));

    widgets.add(AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Material_Create,
      ViewUtil.importIcon("导入零件", (){
        selectFileToImport(partData);

      }),
    ),);

    if(newParms.isNotEmpty){

      widgets.add( Text(
        '变动实价：',
        style: TextStyle(fontSize: ViewUtil.fontSize(20)),
      ));
      for(PriceParm parm in newParms){
        widgets.add(
            SizedBox(width: 180,
                child:
                ShadInput(
                  suffix: Text(parm.unit??"",style: TextStyle(fontSize: ViewUtil.fontSize(18)),),
                  prefix: Text("${parm.name}:",style: TextStyle(fontSize: ViewUtil.fontSize(18)),),
                  textAlign: TextAlign.end,
                  enabled: parm.handle==0,
                  initialValue: parm.handle==0? (parm.value.isNotEmpty?parm.value.toString():""):getRuleString(parm.rule),
                  placeholder: Text("请输入${parm.name}"),
                  onChanged: (value){
                    debugPrint(value);
                    parm.value=value;
                    updateValue(parm);
                  },
                )));
      }
    }


    return widgets;
  }


  Widget materialItemView(PricePart partData){
    var tableHeight=_calculateTableHeight(partData.childMaterialList.length);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            SizedBox(width: ViewUtil.screenWidth(40),),
           // Text('${getCrumbName(partData)}',style: TextStyle(fontSize: ViewUtil.fontSize(24),fontWeight: FontWeight.bold),),
            getCrumbView(),

            SizedBox(width: ViewUtil.screenWidth(20),),
            const SizedBox(width: 20),

            Expanded(child: Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              children: [

                Text(
                  '${partData.code}    ',
                  style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                ),
                if(AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Price))
                Text(
                  '￥ ',
                  style: TextStyle(fontWeight: FontWeight.bold,fontSize: ViewUtil.fontSize(18)),
                ),
                if(AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Price))
                Text(
                  '${MathUtil.formatDouble(partData.dPrice, 2)}    ',
                  style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                ),


                if(partData.childMaterialList.isNotEmpty)
                  Text(
                    '精算价格￥ ',
                    style: TextStyle(fontWeight: FontWeight.bold,fontSize: ViewUtil.fontSize(18)),
                  ),

                if(partData.childMaterialList.isNotEmpty)
                  Text(
                    '${MathUtil.formatDouble(partData.price, 2)}    ',
                    style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                  ),

                //  const SizedBox(width: 20),

                if(partData.typeId==GlobalData.compressorId)
                  Text(
                    '建议换热面积 ${partData.area1.isEmpty?"-":partData.area1.isEmpty}:${partData.area2.isEmpty?"-":partData.area2.isEmpty}  ',
                    style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                  ),

                if(partData.typeId==GlobalData.compressorId)
                  Text(
                    '建议铜配重量 ${partData.weight1.isEmpty?"-":partData.weight1.isEmpty}:${partData.weight2.isEmpty?"-":partData.weight2.isEmpty}  ',
                    style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                  ),

                if(partData.typeId==GlobalData.condenserId||partData.typeId==GlobalData.evaporator)
                  Text(
                    '换热面积 ${partData.area1.isEmpty?"-":partData.area1.isEmpty}  ',
                    style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                  ),

                if(partData.typeId==GlobalData.fluorineId)
                  Text(
                    '铜配重量 ${partData.weight1.isEmpty?"-":partData.weight1.isEmpty} ',
                    style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                  ),

                Text(
                  '${getPartSpec(partData)}',
                  style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                ),


              ],
            )),

            ViewUtil.editIcon("编辑", (){
              editMaterial(partData);
            }),
            // IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_double_arrow_down_sharp:Icons.keyboard_double_arrow_up_sharp),
            //   color:ColorUtil.colorBlue,
            //   iconSize: ViewUtil.screenWidth(35),onPressed: (){
            //     bool result= getIsShow(partData.id);
            //     result=!result;
            //     showMaps[partData.id]=result;
            //      setState(() {
            //     });
            //   },),
            // ViewUtil.editIcon((){
            //
            //   editMaterial(partData);
            // }),
            // ViewUtil.delIcon((){
            //   showDelPart(partData);
            // }),
            // IconButton(icon:  Icon( Icons.dataset),
            //   color:ColorUtil.colorBlue,
            //   iconSize: ViewUtil.screenWidth(35),onPressed: (){
            //     showShadSheet(
            //
            //       side: ShadSheetSide.right,
            //       context: context,
            //       builder: (context) =>   MaterialListVC(pricePart:partData , callback: () {
            //         //回调
            //         // getDetail();
            //       },),
            //     );
            //   },),
          ],
        ),
        ViewUtil.lineView(),
        Container(
          margin: EdgeInsets.only(left: ViewUtil.screenWidth(15),right: ViewUtil.screenWidth(10),bottom: ViewUtil.screenHeight(10)),
          child:  Card(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 10),
              // Row(
              //   children: [
              //     SizedBox(width: ViewUtil.screenWidth(20),),
              //     Text('型号概况',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              //     Expanded(child: Container()),
              //   ],
              // ),
              // const SizedBox(height: 10),
              Container(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30),right: 0),
                width: double.infinity,
                child: getRemarkViews(partData),
              ),
              // Padding(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30),right: 0),child: Wrap(
              //   crossAxisAlignment: WrapCrossAlignment.center,
              //   runAlignment: WrapAlignment.start,
              //   direction: Axis.horizontal, // 水平方向排列（默认）
              //   alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
              //   spacing: 10, // 子组件横向间距
              //   runSpacing: 0, // 换行后纵向间距
              //   children: getRemarkViews(partData),
              // ),),

              const SizedBox(height: 10),
            ],
          ),
        ),),

        Container(
          margin: EdgeInsets.only(left: ViewUtil.screenWidth(15),right: ViewUtil.screenWidth(10),bottom: ViewUtil.screenHeight(10)),
          child:  Card(
            color: Colors.white,

            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 10),
                Row(
                  children: [
                    SizedBox(width: ViewUtil.screenWidth(28),),
                    Text('型号参数',style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: ViewUtil.fontSize(18)),),
                    Expanded(child: Container()),
                  ],
                ),
                const SizedBox(height: 20),
                Padding(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30)),child: Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  runAlignment: WrapAlignment.start,
                  direction: Axis.horizontal, // 水平方向排列（默认）
                  alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                  spacing: 10, // 子组件横向间距
                  runSpacing: 8, // 换行后纵向间距
                  children: getPartParmViews(partData),
                ),),


                const SizedBox(height: 10),
              ],
            ),
          ),
        ),

        if(partData.parmList.isNotEmpty)
        Visibility(
            visible:false,
            child: Padding(

              padding: EdgeInsets.only(left: ViewUtil.screenWidth(15)),
              child: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                runAlignment: WrapAlignment.start,
                direction: Axis.horizontal, // 水平方向排列（默认）
                alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                spacing: 10, // 子组件横向间距
                runSpacing: 0, // 换行后纵向间距
                children: paramView(partData),
              ),)),

        if(partData.childParmList.isNotEmpty)

          Padding(

            padding: EdgeInsets.only(left: ViewUtil.screenWidth(15)),
            child: Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              runAlignment: WrapAlignment.start,
              direction: Axis.horizontal, // 水平方向排列（默认）
              alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
              spacing: 10, // 子组件横向间距
              runSpacing: 0, // 换行后纵向间距
              children: getGlobalPara(partData),
            ),),



        if(partData.childParmList.isNotEmpty)
        Visibility(
            visible:true,
            child:

            Container(
              // 应用计算出的高度
              alignment: Alignment.centerLeft,
              margin: EdgeInsets.only(left: ViewUtil.screenWidth(15),right: ViewUtil.screenWidth(10),bottom: ViewUtil.screenHeight(10)),
              height: tableHeight>400?400:tableHeight,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
                borderRadius: BorderRadius.circular(8),
              ),
              child:

              DataTable2(
                columnSpacing: 12,
                horizontalMargin: 12,
                minWidth: 40000,
                isHorizontalScrollBarVisible:true,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                // 表头
                columns: getTableHead(partData),

                // 表格内容（行高固定）
                rows: partData.childMaterialList.map((item) {
                  return DataRow(cells: getTableItem(partData,item));
                }).toList(),
              ),
            )
        ),
      ],
    );
  }


   getRemarkViews(PricePart partData){

    Map remarkValues={};
    List<TextSpan> list=[];
    String names="";
    if(partData.remarkData.isNotEmpty){
      List list=jsonDecode(partData.remarkData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    for(PriceParm parm in partData.remarkList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="--";
      bool hasAdd=false;
      if(remarkValues.containsKey(parm.id)&&remarkValues[parm.id].length>0){
        initValue=remarkValues[parm.id];
        hasAdd=true;
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
          hasAdd=true;
        }
      }
      parm.value=initValue;
      names=names+"${parm.name}:"+initValue+parm.unit+"    ";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$initValue${parm.unit}    "));
      // widgets.add(
      //     SizedBox(width: 220,
      //         child:
      //         Row(children: [
      //           Text("${parm.name}:",style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
      //           Text(initValue,style: TextStyle(fontSize: ViewUtil.fontSize(20))),
      //           Text(parm.unit??"",style: TextStyle(fontSize: ViewUtil.fontSize(20))),
      //         ],)));
    }
    return Text.rich(TextSpan(style: DefaultTextStyle.of(context).style, children: list),style: TextStyle(fontSize: ViewUtil.fontSize(18)),);
    //return Text(names,style: TextStyle(fontSize: ViewUtil.fontSize(18)),);
  }


  List<Widget> getPartParmViews(PricePart partData){
    List<Widget> widgets=[];
    Map remarkValues={};
    if(partData.parmData.isNotEmpty){
      List list=jsonDecode(partData.parmData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    for(PriceParm parm in partData.partParmList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="--";
      bool hasAdd=false;
      if(remarkValues.containsKey(parm.id)&&remarkValues[parm.id].length>0){
        initValue=remarkValues[parm.id];
        hasAdd=true;
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
          hasAdd=true;
        }
      }
      parm.value=initValue;
      widgets.add(
          SizedBox(width: 400,
              child:
              Row(children: [
                Container(width: 200,child: Text("${parm.name}:",style: TextStyle(fontSize: ViewUtil.fontSize(18),color: !hasAdd&&parm.required==1?Colors.red:Colors.black),),),
                Text(initValue,style: TextStyle(fontSize: ViewUtil.fontSize(18))),
                Text(parm.unit??"",style: TextStyle(fontSize: ViewUtil.fontSize(18))),
              ],)));
    }
    return widgets;
  }

  List<DataColumn2> getTableHead(PricePart material){
    List<DataColumn2> widgets=[];
    // widgets.add(const DataColumn2(
    //   label: Text('  操作'),
    //   fixedWidth: 110,
    // ),);
    widgets.add(const DataColumn2(
      label: Text('￥单价'),
      fixedWidth: 100,
    ),);
    for(var i=0;i<material.childParmList.length;i++){
      var item=material.childParmList[i];
      if(i!=material.childParmList.length-1){
        widgets.add(DataColumn2(label: Text(item.name+getParmUnit(item)),fixedWidth: 100,));

      }else{
        widgets.add(DataColumn2(label: Text(item.name+getParmUnit(item)),fixedWidth: 500,));
      }

    }

    return widgets;
  }

  void editMaterial(PricePart priceData){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialEditParmVC(pricePart:priceData , callback: () {
        //回调
      },),
    );
  }


  getParmUnit(PriceParm item){
    if(item.unit!=null&&item.unit.isNotEmpty){
      return "(${item.unit})";
    }else{
      return "";
    }
  }

  List<DataCell> getTableItem(PricePart partData,PriceMaterial material){
    List<DataCell> widgets=[];
    // widgets.add(DataCell(Row(children: [
    //
    //   ViewUtil.editIcon('编辑材料',(){
    //     showShadSheet(
    //       barrierColor: Colors.transparent,
    //       side: ShadSheetSide.right,
    //       context: context,
    //       builder: (context) =>  MaterialListEditVC(pricePart:partData ,priceMaterial: material, callback: () {
    //         //回调
    //       },),
    //     );
    //
    //   }),
    //   ViewUtil.delIcon('删除材料',(){
    //     delMaterial(material);
    //   })
    // ],)));
    widgets.add(DataCell(Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Text(MathUtil.formatDouble(material.price, 2)),
    )));
    for(var item in partData.childParmList){
      widgets.add(DataCell(Padding(
        padding: const EdgeInsets.symmetric(vertical: 12),
        child:

        GestureDetector(
          onTap: (){
            // showShadSheet(
            //   barrierColor: Colors.transparent,
            //   side: ShadSheetSide.right,
            //   context: context,
            //   builder: (context) =>   MaterialChildListEditVC(pricePart:partData ,priceMaterial: material, callback: () {
            //     //回调
            //   },),
            // );
          },
          child: Text(getParmValue(item.id,material.data)),
        ),
      )));
    }

    return widgets;
  }

  getParmValue(String id,var data){
    if(data==null||data.length==0)return "";
    List datas=json.decode(data);
    var values={};
    for(var item in datas){
      values[item["id"]]=item["value"];
    }

    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    bool isNum=MathUtil.isNumeric(value);
    return isNum?MathUtil.formatDouble(double.parse(value), 2):value;
  }

  getMaterialRuleString(PriceParm parm,var data){
    if(data==null||data.length==0)return getRuleString(parm.rule);

    List datas=json.decode(data);
    String value="";
    for(var item in datas){
      if(item["id"]==parm.id){
        var handle=item["handle"];
        var v=item["rule"];
        if(handle!=null&&handle==1&&v!=null){
          if(v.contains("[")){
            value=v;
          }
        }
        break;
      }

    }
    if(value.isNotEmpty){
      return getRuleString(value);
    }else{
      return getRuleString(parm.rule);
    }
  }





  List<Widget> paramView(PricePart material){
    List<Widget> widgets=[];
    for(PriceParm parm in material.parmList){
      widgets.add(SizedBox(width: 140,
        child:
        ShadInput(
          prefix: Text(parm.name),
          suffix: Text(parm.unit??""),
          textAlign: TextAlign.end,
          placeholder: Text("请输入${parm.name}"),

          enabled: parm.handle==0,
          onPressedOutside: (value){

          },
          onEditingComplete: (){
            updateValue(parm);
          },
          initialValue: parm.handle==0? (parm.value.isNotEmpty?parm.value.toString():""):getRuleString(parm.rule),
          onChanged: (value){
            debugPrint(value);
            parm.value=value;

          },
        ),));
    }
    return widgets;
  }

  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }

  void updateValue(PriceParm parm){
    var parms={
      "id":parm.id,
      "value":parm.value
    };
    BaseRequest.postHttp('price/editparmvalue',parameters: parms, canTip: false, context: context, onSuccess: (data){
      //countPrice();
      eventBus.fire(EventRefreshBase());
    }, onError: (error){});
  }


  getPartSpec(PricePart partData){
    var spec=partData.spec;
    var value="";
    if(spec.isNotEmpty){
     var  specsList=jsonDecode(spec);
     for(var i=0;i<specsList.length;i++){
       var item=specsList[i];
       var str="${item["name"]}:${item["value"]}";
       value="$value$str";
       if(i!=specsList.length-1){
         value="$value | ";
       }

     }
     }

    return value;
  }
  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }


  @override
  void dispose() {

    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: materialView(),
    );
  }

  void submitPart(){
    if (formKey.currentState!.saveAndValidate()) {
      var values= formKey.currentState!.value;
      var name=values["name"];
      var parm={
        "name":name,
        "id":pricePart.id,
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("保存成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }

  void addMaterial(PriceSerial serial){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialAddVC(pricePart:pricePart , callback: () {
        //回调
        getDetail();
      },),
    );
  }






  void showDelPart(PricePart partData){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${partData.name}吗?'),
        description:  Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将删除${partData.name}',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              uploadDelPart(pricePart);

            },
          ),
        ],
      ),
    );
  }

  void uploadDelPart(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/delpricemodel",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getDetail();
        Navigator.of(context).pop(false);
        eventBus.fire(EventRefreshBase());
      }
    }, onError: (error){

    });
  }



  void delMaterial(PriceMaterial material){
    var parm={
      "id":material.id,
    };
    BaseRequest.postHttp("price/materialitemdel",parameters: parm, canTip: true, context: context, onSuccess: (data){

      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getDetail();
        eventBus.fire(EventRefreshBase());
      }

    }, onError: (error){

    });
  }


     getIsShow(String id){
      bool result=false;
      if(showMaps.containsKey(id)){
        return showMaps[id];
      }
      return result;
    }



  void selectFileToImport(PricePart partData)async{
    FilePickerResult? result = await FilePicker.platform.pickFiles(
    );

    if (result != null) {
      File file = File(result.files.single.path!);
      debugPrint(file.path);
      requestToUpload(file.path,partData);
    } else {
      // User canceled the picker
    }
  }

  void requestToUpload(String path,PricePart partData){
    BaseRequest.uploadToImportMaterial(path: path, partId: partData.id, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("操作成功");
        getDetail();
        eventBus.fire(EventRefreshBase());
      }

    }, onError: (error){});
  }


  getMaterialUniqueRule(PriceParm parm ,PriceMaterial material){
    var uniqueRule="";
    var data=material.data;
    if(data==null||data.length==0)return parm.rule;
    List datas=json.decode(data);
    for(var item in datas){
      var id=item["id"];
      if(id==parm.id){
        var rule=item["rule"];
        if(rule!=null&&rule.toString().isNotEmpty){
          uniqueRule=rule;
        }
        break;
      }
    }

    if(uniqueRule.isNotEmpty){
      return uniqueRule;
    }else{
      return parm.rule;
    }
  }

  countPartPrice(PricePart partData,Map allValue){
    //先判断是否有子级数据，有的话，则直接用
    if(partData.childMaterialList.isNotEmpty&&partData.childParmList.isNotEmpty){
      for(PriceParm parm in partData.childParmList){
        for(PriceMaterial material in partData.childMaterialList){
          if(parm.handle==0){
            allValue["${material.id}_${parm.id}"]=getParmValue(parm.id,material.data);
          }else{
            var rule=getMaterialUniqueRule(parm, material);
            var value=getMaterialRuleValue(rule,material.id, allValue);
            allValue["${material.id}_${parm.id}"]=value;
            List datas=json.decode(material.data);
            bool hasAdd=false;
            for(var item in datas) {
              var id = item["id"];
              if(id==parm.id){
                item["value"]=value.toString();
                hasAdd=true;
                break;
              }
            }
            if(!hasAdd){
              datas.add({"id":parm.id,"value":value.toString()});
            }

            material.data=json.encode(datas);
          }
        }
      }
    }else{
      var parmList= partData.parmList;
      for(PriceParm parm in parmList){
        if(parm.handle==0){
          allValue[parm.id]=parm.value;
        }
      }
      for(PriceParm parm in parmList){
        if(parm.handle==1){
          var value=getRuleValue(parm.rule, allValue);
          allValue[parm.id]=value;
        }
      }
    }
  }


  void countPrice(PricePart partData){
    //先计算全局参数
    Map allValue={};
    //先计算一遍全局参数
    for(PriceParm parm in partData.parmList){
      if(parm.handle==0){
        allValue[parm.id]=parm.value;
      }
    }
    for(PriceParm parm in partData.parmList){
      if(parm.handle==1){
        var value=getRuleValue(parm.rule, allValue);
        allValue[parm.id]=value;
      }
    }
    countPartPrice(partData,allValue);

    //品牌
    //公式以及材料列表、参数都配置，才生效
    if(partData.childMaterialList.isNotEmpty&&partData.childMaterialList.isNotEmpty&&partData.materialRule.isNotEmpty){
      double partPrice=0;
      for(PriceMaterial material in partData.childMaterialList){

        var value=getMaterialRuleValue(partData.materialRule, material.id, allValue);
        material.price=double.parse('$value');
        partPrice+=material.price;
      }
      partData.price=partPrice;

    }else{
      //没有子数据的时候
      if(partData.rule.isNotEmpty&partData.parmList.isNotEmpty){
        var rule=partData.rule;
        var value=getRuleValue(rule, allValue);
        partData.price=double.parse('$value');

      }else{
        partData.price=0;
      }
    }

  }


  getMaterialRuleValue(var rule,var materialId,Map allValue){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          if(allValue.containsKey(materialId+"_"+rule.value)){
            var value=allValue[materialId+"_"+rule.value];
            if(value.toString().isEmpty){
              value="0";
            }
            ruleStr="$ruleStr$value";
          }

          else if(allValue.containsKey(rule.value)){
            var value=allValue[rule.value];
            if(value.toString().isEmpty){
              value="0";
            }
            ruleStr="$ruleStr$value";
          }else{
            ruleStr="${ruleStr}0";
          }
        }
      }
    }
    return MathUtil.countExpression(ruleStr);
  }

  getRuleValue(var rule,Map allValue){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          if(allValue.containsKey(rule.value)){
            ruleStr="$ruleStr${allValue[rule.value]}";
          }else{
            return 0;
          }

        }
      }
    }

    return MathUtil.countExpression(ruleStr);
  }

}
